package com.jhd.fuzhou.view.dossier;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.service.SpecialService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.BusinessStatus;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.daily.DailySupervisionActivity;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.random.DoubleStepOneActivity;
import com.jhd.fuzhou.view.special.SpecialActivity;
import com.jhd.fuzhou.vo.CountyVo;
import com.jhd.fuzhou.vo.DeptVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.MajorSpeciality;
import com.jhd.fuzhou.vo.MinorSpeciality;
import com.jhd.fuzhou.vo.OrganizationVo;
import com.jhd.fuzhou.vo.SearchUnit;
import com.jhd.fuzhou.vo.SupervisedUnitVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.TimeUtil.getTimeDialog3;

/*本底档案*/
public class DossierActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView iv_back;//顶部返回按钮
    @BindView(R.id.lin_select)
    LinearLayout lin_select;//顶部筛选按钮
    @BindView(R.id.iv_cancel)ImageView iv_cancel;//搜索框取消按钮
    @BindView(R.id.et_search)
    EditText et_search;//搜索框输入
    @BindView(R.id.rv_company)
    RecyclerView rv_company;//企业的列表
    @BindView(R.id.btn_add_report)
    Button btn_add_report;//底部添加报告按钮
    @BindView(R.id.tv_loading)
    TextView tv_loading;//
    private Context context=this;
    private AlertDialog _alertDialog=null;
    private LinearLayout lin_grade;
    private SearchUnit searchUnit;
    private LinearLayoutManager layoutManager;
    private ProgressDialog _dialog;
    private List<SupervisedUnitVo> supervisedUnitVoList =new ArrayList<>();
    private String[] manageStatusNameList=new String[]{"正常","关闭","暂停"};//1,0,2
    private String[] gradeList=new String[]{"全部","A","B","C","未评级"};//"不予评级"
    private String[] manageStatusIdList=new String[]{"1","0","2"};//1,0,2
    private boolean[] manageStatus=new boolean[]{false,false,false};
    private List<MajorSpeciality> majorSpecialityList=null;
    private List<MinorSpeciality> minorSpecialityList=null;
    private List<CountyVo> countyVoList=null;//经营地址
    private List<OrganizationVo> organizationVoList =null;//监管机构
    private RecyclerView rv_specialityCategory,rv_specialityDetail,rv_superviseDept,rv_manage_status,rv_grade;
    private UnitAdapter unitAdapter;
    private Gson gson = new Gson();
    private ListView listView;
    private PopupWindow popup;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_dossier);
    }


    private void refresh(){
        supervisedUnitVoList.clear();
        searchUnit=new SearchUnit();
        searchUnit.setPageIndex(1);
        searchUnit.setPageNum(1);//默认只有一页
        searchUnit.setKeyword(et_search.getText().toString());
        getSupervisedUnitList();
    }
    @Override
    protected void processLogic() {
        onBack();
        layoutManager = new LinearLayoutManager(context);
        rv_company.setLayoutManager(layoutManager);
        rv_company.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                if(lastCompletelyVisibleItemPosition==layoutManager.getItemCount()-1){
                    tv_loading.setVisibility(View.VISIBLE);
                    searchUnit.setPageIndex(searchUnit.getPageIndex()+1);
                    if(searchUnit.getPageIndex()<=searchUnit.getPageNum()){
                        tv_loading.setText(getString(R.string.loading));
                        getSupervisedUnitList();
                    }else{
                        tv_loading.setText(getString(R.string.arrival_bottom));
                    }
                }else{
                    tv_loading.setVisibility(View.GONE);//没到底部，隐藏
                }
            }
        });
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search.getText().toString());
                supervisedUnitVoList.clear();
                getSupervisedUnitList();
                return false;
            }
        });
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().equals("")){
                    searchUnit.setPageIndex(1);
                    searchUnit.setKeyword(s.toString());
                    supervisedUnitVoList.clear();
                    getSupervisedUnitList();
                    iv_cancel.setVisibility(View.GONE);
                }else{
                    iv_cancel.setVisibility(View.VISIBLE);
                }
            }
        });

        refresh();
    }

    @OnClick({R.id.iv_back,R.id.lin_select,R.id.iv_cancel,R.id.btn_add_report})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.lin_select://点击跳筛选弹窗
                dialogShow();
                break;
            case R.id.iv_cancel://点击清空输入框，并隐藏取消按钮
                et_search.setText("");
                iv_cancel.setVisibility(View.GONE);
                break;
            case R.id.btn_add_report://点击跳转添加报告按钮
                Intent intent=new Intent(context, DossierUpdateActivity.class);
                startActivityForResult(intent,1);
                break;
        }
    }

    //获取地区列表
    private void getCountySelector(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SpecialService vs = retrofit.create(SpecialService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("cityCode","361000");
        Call<JsonForResult> jsonForResultCall = vs.getCountySelector(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        countyVoList = JSON.parseArray(jsonForResult.getData().toString(), CountyVo.class);
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    //获取获取监管机构
    private void getOrgSelector(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Call<JsonForResult> jsonForResultCall = vs.getOrgSelector(application.getAccessToken());//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        organizationVoList = JSON.parseArray(jsonForResult.getData().toString(), OrganizationVo.class);
                        setSuperviseDeptButton(rv_superviseDept);
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    //获取所属专业列表
    private void getMajorSpecialitySelector(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Call<JsonForResult> jsonForResultCall = vs.getMajorSpecialitySelector(application.getAccessToken());//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        majorSpecialityList = JSON.parseArray(jsonForResult.getData().toString(), MajorSpeciality.class);
                        setMajorButton(rv_specialityCategory);
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    /*设置量化等级的选择*/
    public void setGradeButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 3);
        recyclerView.setLayoutManager(layoutManage);
        GradeAdapter recyclerAdapter=new GradeAdapter(gradeList);
        recyclerView.setAdapter(recyclerAdapter);
    }
    public class GradeAdapter extends RecyclerView.Adapter<GradeAdapter.ViewHolder> {
        private String[] grade;
        private int checkPosition=0;//默认选中全部

        public GradeAdapter(String[] grade) {
            this.grade = grade;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            ViewHolder viewHolder = new ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.rb_radio.setText(grade[position]);
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    if(grade[checkPosition].equals("全部")){
                        searchUnit.setMainQuantizationLevel(null);
                    }else{
                        searchUnit.setMainQuantizationLevel(grade[checkPosition]);
                    }
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return grade.length;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }

    /*设置所属专业的选择*/
    public void setMajorButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context,2);
        recyclerView.setLayoutManager(layoutManage);
        if(majorSpecialityList!=null){
            MajorAdapter recyclerAdapter=new MajorAdapter(majorSpecialityList);
            recyclerView.setAdapter(recyclerAdapter);
        }
    }
    public class MajorAdapter extends RecyclerView.Adapter<MajorAdapter.ViewHolder> {
        private List<MajorSpeciality> majorSpecialityList;
        private int checkPosition=-1;

        public MajorAdapter(List<MajorSpeciality> majorSpecialityList) {
            this.majorSpecialityList = majorSpecialityList;
        }

        @NonNull
        @Override
        public MajorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            MajorAdapter.ViewHolder viewHolder = new MajorAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MajorAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(majorSpecialityList.get(position).getName());
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(checkPosition==position){
                        holder.rb_radio.setChecked(false);
                        checkPosition=-1;
                        searchUnit.setSpecialityCategory(null);
                        minorSpecialityList.clear();
                        setMinorButton(rv_specialityDetail);
                    }else{
                        checkPosition=position;
                        searchUnit.setSpecialityCategory(majorSpecialityList.get(position).getName());
                        searchUnit.setSpecialityCategoryId(majorSpecialityList.get(position).getId());
                        notifyDataSetChanged();
                        getMinorSpecialitySelector();
                    }
                    if(majorSpecialityList.get(position).getName().equals("公共场所")){
                        lin_grade.setVisibility(View.VISIBLE);
                        setGradeButton(rv_grade);
                    }else{
                        lin_grade.setVisibility(View.GONE);
                        searchUnit.setMainQuantizationLevel(null);
                    }
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }

        @Override
        public int getItemCount() {
            return majorSpecialityList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }
    //根据所属专业的Id获取专业明细列表
    private void getMinorSpecialitySelector(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("parentId",searchUnit.getSpecialityCategoryId());
        Call<JsonForResult> jsonForResultCall = vs.getMinorSpecialitySelector(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()==null){
                            minorSpecialityList=new ArrayList<MinorSpeciality>();
                        }else{
                            minorSpecialityList = JSON.parseArray(jsonForResult.getData().toString(), MinorSpeciality.class);
                        }
                        setMinorButton(rv_specialityDetail);
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    /*设置专业明细的选择*/
    public void setMinorButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManage);
        if(minorSpecialityList!=null){
            MinorAdapter recyclerAdapter=new MinorAdapter(minorSpecialityList);
            recyclerView.setAdapter(recyclerAdapter);
        }
    }
    public class MinorAdapter extends RecyclerView.Adapter<MinorAdapter.ViewHolder> {
        private List<MinorSpeciality> minorSpecialityList;
        private int checkPosition=-1;
        public MinorAdapter(List<MinorSpeciality> minorSpecialityList) {
            this.minorSpecialityList = minorSpecialityList;
        }
        @NonNull
        @Override
        public MinorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            MinorAdapter.ViewHolder viewHolder = new MinorAdapter.ViewHolder(itemView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(@NonNull MinorAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(minorSpecialityList.get(position).getName());
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(checkPosition==position){
                        holder.rb_radio.setChecked(false);
                        checkPosition=-1;
                        searchUnit.setSpecialityDetail(null);
                    }
                    checkPosition=position;
                    searchUnit.setSpecialityDetail(minorSpecialityList.get(position).getName());
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }
        @Override
        public int getItemCount() {
            return minorSpecialityList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }

    /*设置监管部门*/
    public void setSuperviseDeptButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 2);
        recyclerView.setLayoutManager(layoutManage);
        if(organizationVoList !=null){
            DeptVoAdapter recyclerAdapter=new DeptVoAdapter();
            recyclerView.setAdapter(recyclerAdapter);
        }
    }
    public class DeptVoAdapter extends RecyclerView.Adapter<DeptVoAdapter.ViewHolder> {
        private int checkPosition=-1;
        @NonNull
        @Override
        public DeptVoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            DeptVoAdapter.ViewHolder viewHolder = new DeptVoAdapter.ViewHolder(itemView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(@NonNull DeptVoAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(organizationVoList.get(position).getName());
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    searchUnit.setSuperviseDeptId(organizationVoList.get(position).getId());
                    notifyDataSetChanged();
                }
            });
            if(position==checkPosition){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }
        @Override
        public int getItemCount() {
            return organizationVoList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }
    /*设置经营状态*/
    public void setManageStatusButton(RecyclerView recyclerView){
        GridLayoutManager layoutManage = new GridLayoutManager(context, 3);
        recyclerView.setLayoutManager(layoutManage);
        ManageStatusAdapter recyclerAdapter=new ManageStatusAdapter();
        recyclerView.setAdapter(recyclerAdapter);

    }
    public class ManageStatusAdapter extends RecyclerView.Adapter<ManageStatusAdapter.ViewHolder> {
        @Override
        public ManageStatusAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_radio, parent, false);
            ManageStatusAdapter.ViewHolder viewHolder = new ManageStatusAdapter.ViewHolder(itemView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(@NonNull ManageStatusAdapter.ViewHolder holder, int position) {
            holder.rb_radio.setText(manageStatusNameList[position]);
            holder.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(manageStatus[position]){
                        manageStatus[position]=false;
                    }else{
                        manageStatus[position]=true;
                    }
                    String ss="";
                    for(int i=0;i<manageStatus.length;i++){
                        if(manageStatus[i]){
                            if(ss.equals("")){
                                ss=ss+manageStatusIdList[i];
                            }else{
                                ss=ss+","+manageStatusIdList[i];
                            }
                        }
                    }
                    if(ss.equals("")){
                        searchUnit.setStatus(null);
                    }else{
                        searchUnit.setStatus(ss);
                    }
                    notifyDataSetChanged();
                }
            });
            if(manageStatus[position]){
                holder.rb_radio.setChecked(true);
            }else{
                holder.rb_radio.setChecked(false);
            }
        }
        @Override
        public int getItemCount() {
            return manageStatusNameList.length;
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            RadioButton rb_radio;
            public ViewHolder(View itemView) {
                super(itemView);
                this.rb_radio = itemView.findViewById(R.id.rb_radio);
            }
        }
    }

    //点击筛选，跳弹窗
    public void dialogShow() {
        searchUnit.setSpecialityCategory(null);searchUnit.setSpecialityDetail(null);
        searchUnit.setSuperviseDeptId(null);searchUnit.setStatus(null);
        for(int i=0;i<manageStatus.length;i++){
            manageStatus[i]=false;
        }
        getMajorSpecialitySelector();//首先获取所属专业的列表
        getCountySelector();getOrgSelector();
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_screen_dossier, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        EditText et_search_dialog = (EditText) view.findViewById(R.id.et_search);
        ImageView iv_cancel_dialog = (ImageView) view.findViewById(R.id.iv_cancel);
        TextView tv_registerAddress = (TextView) view.findViewById(R.id.tv_registerAddress);
        LinearLayout lin_county = (LinearLayout) view.findViewById(R.id.lin_county);
        ImageView iv_downUp = (ImageView) view.findViewById(R.id.iv_downUp);
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        Button btn_reset = (Button) view.findViewById(R.id.btn_reset);
        Button btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
        rv_specialityCategory = (RecyclerView) view.findViewById(R.id.rv_specialityCategory);
        rv_specialityDetail = (RecyclerView) view.findViewById(R.id.rv_specialityDetail);
        rv_manage_status = (RecyclerView) view.findViewById(R.id.rv_manage_status);
        rv_superviseDept = (RecyclerView) view.findViewById(R.id.rv_superviseDept);
        lin_grade = (LinearLayout) view.findViewById(R.id.lin_grade);
        rv_grade = (RecyclerView) view.findViewById(R.id.rv_grade);
        setManageStatusButton(rv_manage_status);
        lin_county.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCountyVo(tv_registerAddress);
            }
        });
        btn_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchUnit.setStatus(null);searchUnit.setKeyword(null);searchUnit.setSuperviseDeptId(null);
                searchUnit.setSpecialityCategory(null);searchUnit.setSpecialityDetail(null);
                searchUnit.setManagementProvince(null);searchUnit.setManagementCity(null);
                searchUnit.setStatus(null);
                setMajorButton(rv_specialityCategory);
                if(minorSpecialityList!=null)minorSpecialityList.clear();
                setMinorButton(rv_specialityDetail);
                showCountyVo(tv_registerAddress);
                tv_registerAddress.setText("全部地区");
                setSuperviseDeptButton(rv_superviseDept);
            }
        });
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
                searchUnit.setPageIndex(1);
                searchUnit.setKeyword(et_search_dialog.getText().toString());
                supervisedUnitVoList.clear();
                getSupervisedUnitList();
            }
        });
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        iv_cancel_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_search_dialog.setText("");
                iv_cancel_dialog.setVisibility(View.GONE);
            }
        });
        et_search_dialog.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override
            public void afterTextChanged(Editable s) {
                if(!s.toString().equals("")){
                    iv_cancel_dialog.setVisibility(View.VISIBLE);
                }else{
                    iv_cancel_dialog.setVisibility(View.GONE);
                }
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }
    private void showCountyVo(TextView textView) {
        listView = new ListView(context);
        listView.setDivider(null);//设置分割线
        listView.setVerticalScrollBarEnabled(false);//不显示滑动条
        listView.setAdapter(new CountyVoAdapter(textView));
        popup = new PopupWindow(context);
        popup.setWidth(textView.getWidth()*2);
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(textView, 0, 15);//显示在edit控件的下面0,0代表偏移量
    }
    private class CountyVoAdapter extends BaseAdapter {
        private int checkPosition=-1;private TextView textView;
        public CountyVoAdapter(TextView textView) {
            this.textView = textView;
        }
        @Override
        public int getCount() {
            return countyVoList.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CountyVoAdapter.HolderView holderView = null;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.item_radio, null);
                holderView = new CountyVoAdapter.HolderView();
                holderView.rb_radio = (RadioButton) convertView.findViewById(R.id.rb_radio);
                convertView.setTag(holderView);
            } else {
                holderView = (CountyVoAdapter.HolderView) convertView.getTag();
            }

            holderView.rb_radio.setText(countyVoList.get(position).getName());
            holderView.rb_radio.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checkPosition=position;
                    textView.setText(countyVoList.get(position).getName());
                    searchUnit.setManagementCity(countyVoList.get(position).getCityName());
                    searchUnit.setManagementProvince(countyVoList.get(position).getProvinceName());
                    popup.dismiss();
                }
            });
            return convertView;
        }
        class HolderView {//由于这里用户都是同一个人,就省略用户图像的刷新
            private RadioButton rb_radio;
        }
    }


    public void getSupervisedUnitList() {
        _dialog = new ProgressDialog(context);
        _dialog.setMessage("正在获取被监督单位列表,请稍等...");
        _dialog.show();
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put("pageIndex", searchUnit.getPageIndex());
        params.put("pageSize", 20);
        if(searchUnit.getKeyword()!=null)params.put("keyword", searchUnit.getKeyword());//模糊查询
        if(searchUnit.getSuperviseDeptId()!=null){
            params.put("superviseOrgId",searchUnit.getSuperviseDeptId());
        }else{
            if(application.getOrgId()!=null)params.put("superviseOrgId",application.getOrgId());
        }
        if (searchUnit.getSpecialityCategory() != null)params.put("specialityCategory", searchUnit.getSpecialityCategory());//所属专业
        if (searchUnit.getSpecialityDetail() != null)params.put("specialityDetail", searchUnit.getSpecialityDetail());//明细专业
        if (searchUnit.getManagementProvince() != null)params.put("managementProvince", searchUnit.getManagementProvince());//经营省份
        if (searchUnit.getManagementCity() != null)params.put("managementCity", searchUnit.getManagementCity());//经营市
        if (searchUnit.getStatus() != null)params.put("businessStatus", searchUnit.getStatus());//经营市
        if (searchUnit.getMainQuantizationLevel() != null)params.put("mainQuantizationLevel", searchUnit.getMainQuantizationLevel());// A、B、C、不予评级，未评级，只有选择“公共场所”才会出现评级选项
        Call<JsonForResult> jsonForResultCall = vs.getSupervisedUnitList(application.getAccessToken(), params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                if(_dialog != null)_dialog.cancel();
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            List<SupervisedUnitVo> supervisedUnitVos = JSON.parseArray(jsonForResult.getData().toString(), SupervisedUnitVo.class);
                            for (SupervisedUnitVo supervisedUnitVo : supervisedUnitVos) {
                                supervisedUnitVoList.add(supervisedUnitVo);
                            }
                            if (searchUnit.getPageIndex() == 1) {
                                unitAdapter = new UnitAdapter();
                                rv_company.setAdapter(unitAdapter);
                            } else {
                                tv_loading.setVisibility(View.GONE);
                                unitAdapter.notifyDataSetChanged();
                            }
                            searchUnit.setPageNum(jsonForResult.getTotal()/20+1);
                        } else {
                            unitAdapter = new UnitAdapter();
                            rv_company.setAdapter(unitAdapter);
                            tv_loading.setText(context.getString(R.string.arrival_bottom));
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
//                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                if(_dialog != null)_dialog.cancel();
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public class UnitAdapter extends RecyclerView.Adapter<UnitAdapter.ViewHolder> {
        @Override
        public UnitAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_company, parent, false);
            UnitAdapter.ViewHolder viewHolder = new UnitAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull UnitAdapter.ViewHolder holder, int position) {
            holder.tv_legalRepresentative.setText(supervisedUnitVoList.get(position).getLegalRepresentative());
            BusinessStatus.setText(holder.tv_business_status,supervisedUnitVoList.get(position).getBusinessStatus());
            holder.tv_speciality.setText(supervisedUnitVoList.get(position).getSpecialityCategory() + " - " + supervisedUnitVoList.get(position).getSpecialityDetail());
            if (supervisedUnitVoList.get(position).getRegisterAddress() != null) {
                holder.unitAddress.setText(supervisedUnitVoList.get(position).getRegisterAddress());
            } else {
                holder.unitAddress.setText(supervisedUnitVoList.get(position).getRegisterProvince() + supervisedUnitVoList.get(position).getRegisterCity());
            }
            holder.tv_unitName.setText(supervisedUnitVoList.get(position).getUnitName());
            holder.btn_add_report.setText("修改");
            holder.btn_add_report.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, DossierUpdateActivity.class);
                    intent.putExtra("id", supervisedUnitVoList.get(position).getId());
                    startActivityForResult(intent,1);
                }
            });
            if(supervisedUnitVoList.get(position).equals("A")){
                holder.iv_grade.setBackgroundResource(R.mipmap.ic_grade_a);
            }else if(supervisedUnitVoList.get(position).equals("B")){
                holder.iv_grade.setBackgroundResource(R.mipmap.ic_grade_b);
            }else if(supervisedUnitVoList.get(position).equals("C")){
                holder.iv_grade.setBackgroundResource(R.mipmap.ic_grade_c);
            }else{
                holder.iv_grade.setBackgroundResource(R.mipmap.ic_grade_no);
            }
        }

        @Override
        public int getItemCount() {
            return supervisedUnitVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_legalRepresentative, tv_speciality, unitAddress, tv_unitName,tv_business_status; //法人，所属专业，地址,被检测单位
            ImageView iv_grade; //等级
            Button btn_add_report;

            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_legalRepresentative = itemView.findViewById(R.id.tv_legalRepresentative);
                this.tv_speciality = itemView.findViewById(R.id.tv_speciality);
                this.unitAddress = itemView.findViewById(R.id.unitAddress);
                this.tv_unitName = itemView.findViewById(R.id.tv_unitName);
                this.iv_grade = itemView.findViewById(R.id.iv_grade);
                this.btn_add_report = itemView.findViewById(R.id.btn_add_report);
                this.tv_business_status=itemView.findViewById(R.id.tv_business_status);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==1){
            refresh();
        }
    }
}